@extends('admin.layout')

@section('content')
<div class="row">
    <div class="col-xs-12">

        <div id="partials"></div>

      <div class="box">
        <div class="box-header ui-sortable-handle">
          <i class="fa fa-user"></i>

          <h3 class="box-title">权限列表</h3>
          <!-- tools box -->
          <div class="pull-right box-tools">
            <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#modal-create">
                <i class="fa fa-plus-circle"></i> 添加权限
            </button>
          </div>
          <!-- /. tools -->
        </div>
        <div class="box-body">
            <div class="box box-info">
                <div class="box-header with-border">
                  <h3 class="box-title">权限查询</h3>

                  <div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse">
                        <i class="fa fa-minus"></i>
                    </button>
                  </div>
                </div>
                <!-- /.box-header -->
                <div class="box-body">
                    <form id="search-form" class="form-horizontal" role="form" action="">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">父分类：</label>
                                    <div class="col-sm-8" id="s_parent_id">
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">权限名：</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" value="" name="display_name" />
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="col-sm-4 control-label">标识：</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" value="" name="name" />
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-3">
                            </div>
                        </div>
                    </form>
                </div>
                <!-- /.box-body -->
                <div class="box-footer clearfix">
                  <a href="javascript:void(0)" id="s_reset" class="btn btn-sm btn-default btn-flat pull-left">重置</a>
                  <a href="javascript:void(0)" id="s_submit" class="btn btn-sm btn-info btn-flat pull-right">查询</a>
                </div>
                <!-- /.box-footer -->
            </div>

            <table id="example" class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>Parent</th>
                        <th>Menu Name</th>
                        <th>Icon</th>
                        <th>Name</th>
                        <th>Menu</th>
                        <th>Sort</th>
                        <th>Operation</th>
                    </tr>
                </thead>
                <tbody></tbody>
                <tfoot>
                    <tr>
                        <th>Parent</th>
                        <th>Menu Name</th>
                        <th>Icon</th>
                        <th>Name</th>
                        <th>Menu</th>
                        <th>Sort</th>
                        <th>Operation</th>
                    </tr>
                </tfoot>
            </table>
        </div>
        <!-- /.box-body -->
      </div>
      <!-- /.box -->
    </div>
    <!-- /.col -->
</div>

@include('admin.permission._modals')

<script id="form-parent" type="text/x-handlebars-template">
    <select name="parent_id" class="form-control">
        @{{#each this}}
            <option value="@{{id}}">@{{display_name}}</option>
        @{{/each}}
    </select>
</script>

<script id="operation" type="text/x-handlebars-template">
    <button type="button" class="btn btn-primary btn-sm btn-edit">
        <i class="fa fa-pencil"></i> 修改
    </button>

    <button type="button" class="btn btn-danger btn-sm btn-del">
        <i class="fa fa-trash-o"></i> 删除
    </button>
</script>

<script id="success" type="text/x-handlebars-template">
    <div class="alert alert-success alert-dismissible">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        <h4><i class="icon fa fa-check"></i> 成功！</h4>
        @{{#if msg}}@{{msg}}@{{/if}}
    </div>
</script>

<script id="errors" type="text/x-handlebars-template">
    <div class="alert alert-warning alert-dismissible">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        <h4><i class="icon fa fa-warning"></i> 提醒！</h4>
        <ul>
        @{{#each this}}
            @{{#each this}}
                <li>@{{this}}</li>
            @{{/each}}
        @{{/each}}
        </ul>
    </div>
</script>

@stop

@section('scripts')
<script>
    var table;
    $(function () {
        get_permission();

        table = $("#example").DataTable({
            "serverSide": true,
            "ajax": {
                "url": "{{ url('admin/permissions') }}",
                "data": function ( d ) {
                    var data = $('#search-form').serializeArray();
                    $.each(data, function( k, v ) {
                        d[v.name] = v.value;
                    });
                }},
            "searchable": false,
            "searching": false,
            "order": [0, 'desc'],
            "ordering": false,
            "paging": true,
            "pageLength": 30,
            "bLengthChange" : false,
            "columns": [
                { "data": "parent_id" },
                { "data": "display_name" },
                { "data": "icon" },
                { "data": "name" },
                { "data": "is_menu" },
                { "data": "sort_order" },
                { "data": null }
            ],
            "columnDefs": [
                {
                    targets: 0,
                    render: function (data, type, row, meta) {
                        return row.parent ? row.parent.display_name : '-';
                    }
                },
                {
                    targets: 2,
                    render: function (data, type, row, meta) {
                        return row.icon ? '<i class="fa fa-'+row.icon+'"></i>' : '';
                    }
                },
                {
                    targets: 4,
                    render: function (data, type, row, meta) {
                        return row.is_menu ? '<i class="fa fa-check"></i>' : '';
                    }
                },
                {
                    targets: 6,
                    render: function (data, type, row, meta) {
                        return Handlebars.compile($("#operation").html());
                    }
                }
            ]
        });

        $('#s_submit').click(function () {
            table.draw();
        });

        $('#s_reset').click(function () {
            $('#search-form').trigger("reset");
        });

    });

    // 初始化权限下拉选择框
    function get_permission(){
        $.ajax({
            url : "{{ url('admin/permissions') }}",
            type: "GET",
            data: { draw: 0, start: 0, length: 1000, parent_id: 0 }
        }).done(function(data, textStatus, jqXHR) {
            var all = [{"id":-1,"name":"","display_name":"请选择..."}];
            var top = [{"id":0,"name":"","display_name":"顶级"}];
            var list = data.data;
            var tpl_permissions = Handlebars.compile($("#form-parent").html());
            $('#s_parent_id').html(tpl_permissions(all.concat(top.concat(list))));
            $('#modal-create .parent_id').html(tpl_permissions(top.concat(list)));
            $('#modal-edit   .parent_id').html(tpl_permissions(top.concat(list)));
        }).fail(function(jqXHR, textStatus, errorThrown){
            partials(jqXHR.responseJSON, jqXHR.status, jqXHR.statusText);
        });
    }

    $("#create-form").submit(function(){
        var obj = $(this);
        $.ajax({
            url : "{{ url('/admin/permissions') }}",
            type: "POST",
            data: $(this).serialize()
        }).always(function() {
            obj.trigger("reset");
            $('#modal-create').modal('hide');
            table.ajax.reload();
        }).done(function(data, textStatus, jqXHR) {
            partials(data, jqXHR.status, jqXHR.statusText);
            get_permission();
        }).fail(function(jqXHR, textStatus, errorThrown){
            partials(jqXHR.responseJSON, jqXHR.status, jqXHR.statusText);
        });
        return false;
    });

    $('#example').on('click', '.btn-del', function () {
        var obj = this.parentNode.parentNode;
        var row = table.row(obj).data();
        $("#delete-form").find("input[name='id']").val(row.id);
        $("#delete-notice-data").html(row.display_name);
        $("#modal-delete").modal("show");
    });

    $("#delete-form").submit(function(){
        var obj = $(this);
        var id  = obj.find("input[name='id']").val();
        if (id <= 0) {
            return false;
        }

        $.ajax({
            url : "{{ url('/admin/permissions') }}/" + id,
            type: "POST",
            data: {
                '_method': 'DELETE',
                '_token': '{!! csrf_token() !!}'
            }
        }).always(function() {
            obj.find("input[name='id']").val(0);
            $('#modal-delete').modal('hide');
            table.ajax.reload();
        }).done(function(data, textStatus, jqXHR) {
            partials(data, jqXHR.status, jqXHR.statusText);
            get_permission();
        }).fail(function(jqXHR, textStatus, errorThrown){
            var text = jqXHR.responseText == '' ? jqXHR.statusText : jqXHR.responseText;
            partials(jqXHR.responseJSON, jqXHR.status, text);
        });
        return false;
    });

    $('#example').on('click', '.btn-edit', function () {
        var obj = this.parentNode.parentNode;
        var row = table.row(obj).data();
        $("#modal-edit").unserializeArray(row).modal("show");
    });

    $("#edit-form").submit(function(){
        var obj = $(this);
        var id  = obj.find("input[name='id']").val();
        if (id <= 0) {
            return false;
        }

        $.ajax({
            url : "{{ url('/admin/permissions') }}/" + id,
            type: "POST",
            data: $(this).serialize()
        }).always(function() {
            obj.find("input[name='id']").val(0);
            obj.trigger("reset");
            $('#modal-edit').modal('hide');
            table.ajax.reload();
        }).done(function(data, textStatus, jqXHR) {
            partials(data, jqXHR.status, jqXHR.statusText);
        }).fail(function(jqXHR, textStatus, errorThrown){
            var text = jqXHR.responseText == '' ? jqXHR.statusText : jqXHR.responseText;
            partials(jqXHR.responseJSON, jqXHR.status, text);
        });
        return false;
    });

    function partials(data, status, text){
        var html;
        var tpl_success = Handlebars.compile($("#success").html());
        var tpl_errors  = Handlebars.compile($("#errors").html());
        if (status == 200) {
            if (data.code == 0) {
                html = tpl_success(data);
            } else {
                html = tpl_errors({"msg":[data.msg]});
            }
        } else if (status == 422) {
            html = tpl_errors(data);
        } else {
            html = tpl_errors({"msg":[text]});
        }
        $('#partials').append(html);

        return true;
    }

    function compactArr(arr1, arr2){
        $.each(arr1, function( k, v ) {
            arr1[k].selected = "";
            $.each(arr2, function( i, t ) {
                if (v.id == t.id) {
                    arr1[k].selected = "checked";
                    return false; //break
                }
            });
        });
        return arr1;
    }
</script>
@stop